const { getThisYearRecord, getHistory, getLastWeekRecord, getRecord, getPeer, getTotal, getHeroTotal, getWordcloud, getNameListByUserIdList, isOpenUser, getToday } = require('./utils/index')
const { getReply, getGodreply, getStar, getGoodMorningReply, getGoodNightReply, getCangtoushi, getJixiong, getHistoryToday, getBirthDay, getDream } = require('./robotApi/index');
const { bindDotaId, unbindDotaId, getDotaIdList, clearDotaIdList, getJxnumber, getJxnumberAgain, getDotaFortuneByWechatId } = require('./api/userList')
const { getMonitorMemberList, addMonitorMember, removeMonitorMember, clearMonitorMember } = require('./api/roomList')
const { getScore, getScoreRank } = require('./api/gameList')
const { playDotaGame } = require('./api/dotagame')
const { randomHero } = require('./utils/dota2helper')
const axios = require('axios')
const cheerio = require('cheerio')

const dotaGameMap = {}

class messageManager {
    constructor() {
        this.fullKeyWordTask = {
            // 'help': this.getHelp,
            '双色球': this.getTwoColorBall,
            '神回复': this.getGod,
            '早安': this.getGoodMorning,
            '晚安': this.getGoodNight,
            '历史上的今天': this.getTodayInHistory,
            '抽签': this.getDraw,
            '重新抽签': this.getDrawAgain,
            '清除监控': this.clearMonitorMember,
            '监控列表': this.getMonitorMemberList,
            '绑定列表': this.getDotaIdList,
            '清除绑定': this.clearDotaIdList,
            '刀塔运势': this.getDotaFortune,
            'random': this.getRandomHero,
            '查询积分': this.getScore,
            '查询积分排名': this.getScoreRank
            // '奥运赛程': this.getOlympic,
            // '中国金牌': this.getChinaGold,
            // '寻找比赛': this.playDota
        }

        this.includeKeyWordTask = {
            '查询周报': this.getWeekRecord,
            '查询年报': this.getYearRecord,
            '查询战绩': this.getRecord,
            '查询队友': this.getTeammate,
            '查询统计': this.getStatistics,
            '查询英雄': this.getHero,
            '查询词云': this.getWordCloud,
            '查询历史': this.getHistory,
            '添加监控': this.addMonitorMember,
            '移除监控': this.removeMonitorMember,
            '添加绑定': this.bindDotaId,
            '解除绑定': this.unbindDotaId,
            '星座运势': this.getStarFortune,
            '生日性格': this.getNatureByBirthday,
            '藏头诗': this.getPoetry,
            '梦见': this.getDreamAbout,
            'roll': this.roll,
            '缘分测试': this.getFateByName,
            '姓名测试': this.getNameTest,
            '天气': this.getWeather,
        }
    }

    init() {
        return new Promise((resolve) => {
            resolve('ok')
        })
    }

    // 处理消息
    async messageHandler(msg) {
        let contact = msg.talker();
        let content = msg.text().trim().toLowerCase();
        let room = msg.room();
        let name = await contact.name()
        let member = await room.member(name)
        let topic = await room.topic();
        try {
            let result = ''

            // @Dota2bot @Dotobot
            if (await msg.mentionSelf() || content.includes('@dotobot') || content.includes('@dota2bot') || content.includes('@replace')) {
                content = content.replace('@dotobot', '').replace('@replace', '').replace('@dota2bot', '').trim()
                if (!Object.keys(this.fullKeyWordTask).includes(content) && !Object.keys(this.includeKeyWordTask).some(item => content.includes(item))) {
                    let res = await getReply(encodeURI(content))
                    result = res.newslist[0].reply
                    return result && room.say(result, member)
                }
            }

            if (Object.keys(this.fullKeyWordTask).includes(content)) {   // 整个关键词触发
                result = await this.fullKeyWordTask[content](msg)
            } else if (Object.keys(this.includeKeyWordTask).some(item => content.includes(item))) {  // 含有关键词触发
                const taskName = Object.keys(this.includeKeyWordTask).find(item => content.includes(item))
                const arg = content.replace(taskName, '').trim()
                result = await this.includeKeyWordTask[taskName](arg, msg)
            } else { // 随机回复 
                // if (Math.ceil(Math.random() * 100) <= 5) {
                //     let res = await getReply(encodeURI(content))
                //     result = res.newslist[0].reply
                // }
            }

            return result && room.say(result, member)

        } catch (error) {
            console.log(error)
            room.say((error || `${'喵'.repeat(Math.ceil(Math.random() * 10))}~`), member)
        }
    }

    // 帮助
    getHelp() {
        return new Promise((resolve, reject) => {
            try {
                resolve(`【Dota2Bot V.1.4.2 PowerBy Yet】
        ====说明====
        查询指令需要输入指令名字+DOTA2好友id(例如:查询战绩215510959)
        绑定游戏ID后,查询指令不再需要输入游戏ID
        ====查询====
        查询战绩
        查询队友
        查询统计
        查询英雄
        查询词云
        查询历史
        查询积分
        查询积分排名
        ====绑定====
        添加绑定
        解除绑定
        清除绑定
        绑定列表
        ====监控====
        添加监控
        移除监控
        清除监控
        监控列表
        ====其他====
        抽签
        早安
        晚安
        藏头诗
        神回复
        星座运势
        @Dota2Bot故事
        @Dota2Bot笑话
        @Dota2Bot情话
        @Dota2Bot舔狗
        @Dota2Bot名言
        @Dota2Bot窍门
        @Dota2Bot台词
        @Dota2Bot彩虹屁
        @Dota2Bot毒鸡汤
        @Dota2Bot绕口令
        @Dota2Bot歇后语
        @Dota2Bot深圳天气
                `)
            } catch (error) {
                reject(error)
            }
        })
    }

    // roll
    roll(max = 100) {
        return new Promise((resolve, reject) => {
            try {
                let number = 0
                max = Number(max) == 0 ? 100 : Number(max)
                if (Number.isNaN(max)) {
                    resolve('请输入正确的格式,如roll  roll100  roll9999')
                    return
                } else {
                    max = max > 10000 ? 10000 : max
                    number = (Math.random() * max).toFixed(0)
                }
                resolve(`你的点数为${number}，点数范围0~${max}`,)
            } catch (error) {
                reject(error)
            }
        })
    }

    // 缘分测试
    getFateByName(name) {
        return new Promise(async (resolve, reject) => {
            try {
                if (name.includes('+')) {
                    let nameList = name.split('+')
                    if (nameList.length === 2 && nameList[0] && nameList[1]) {
                        const res = await axios.post(`https://www.buyiju.com/peidui/xmpd.php?cname1=${encodeURIComponent(nameList[0])}&cname2=${encodeURIComponent(nameList[1])}&submit=%E5%BC%80%E5%A7%8B%E6%B5%8B%E8%AF%95`)
                        const $ = cheerio.load(res.data)
                        let content = $('.content').children()
                        if (content.length > 0) {
                            let message = `\n缘分测试：${nameList[0]}-${nameList[1]}\n---\n配对解析：${content['3'].children[0].data}\n---\n姓名配对指数${content['4'].children[1].data}\n---\n${content['5'].children[0].data}\n${content['5'].children[2].data}\n${content['5'].children[4].data}`
                            resolve(message)
                        }
                    }
                }
                reject('输入格式有误，请输入如 缘分测试郭靖+黄蓉')
            } catch (error) {
                reject('输入格式有误，请输入如 缘分测试郭靖+黄蓉')
            }
        })
    }

    // 姓名测试
    getNameTest(name) {
        return new Promise(async (resolve, reject) => {
            try {
                if (name.length >= 2) {
                    let xs = name.slice(0, 1)
                    let mz = name.slice(1, name.length)
                    let data = `xs=${encodeURIComponent(xs)}&mz=${encodeURIComponent(mz)}&action=test`
                    let config = {
                        method: 'post',
                        url: 'https://xmcs.buyiju.com/',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                        },
                        data: data
                    };

                    const res = await axios(config)
                    const $ = cheerio.load(res.data)
                    let content = $('.content').children()

                    let result = content[6].children[0].data.replace('根据卜易居·名字测试打分，', '') + content[6].children[1].children[0].children[0].data + content[6].children[2].data

                    let main = $('.content .read-content').text().replace('卜易居', '')

                    let message = main + result
                    resolve(message)
                } else {
                    reject('输入格式有误，请输入2个字以上')
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 查询天气
    getWeather(cityName) {
        return new Promise(async (resolve, reject) => {
            try {
                let res = await getReply(encodeURI(`${cityName}天气`))
                const msg = res.newslist[0].reply.replace(RegExp('<br>', 'g'), '\n')
                resolve(msg)
            } catch (error) {
                reject(error)
            }
        })
    }

    // 查询周报
    getWeekRecord(userId, msg) {
        return new Promise(async (resolve, reject) => {
            try {
                if (userId) {
                    const message = await getLastWeekRecord(userId)
                    console.log(message)
                    resolve(message)
                } else {
                    let contact = msg.talker();
                    // 先查是否绑定过id
                    const res = await getDotaIdList({
                        wechatId: contact.id
                    })
                    if (res.data.length > 0) {
                        let message = ''
                        for (const userId of res.data) {
                            let result = await getLastWeekRecord(userId)
                            message = message + result + '\n'
                        }
                        resolve(message)
                    } else {
                        reject('请输入或绑定dota2好友ID!')
                    }
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 查询年报
    getYearRecord(userId, msg) {
        return new Promise(async (resolve, reject) => {
            try {
                if (userId) {
                    const message = await getThisYearRecord(userId)
                    resolve(message)
                } else {
                    let contact = msg.talker();
                    // 先查是否绑定过id
                    const res = await getDotaIdList({
                        wechatId: contact.id
                    })
                    if (res.data.length > 0) {
                        let message = ''
                        for (const userId of res.data) {
                            let result = await getThisYearRecord(userId)
                            message = message + result + '\n'
                        }
                        resolve(message)
                    } else {
                        reject('请输入或绑定dota2好友ID!')
                    }
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 查询战绩
    getRecord(userId, msg) {
        return new Promise(async (resolve, reject) => {
            try {
                if (userId) {
                    const message = await getRecord(userId)
                    resolve(message)
                } else {
                    let contact = msg.talker();
                    // 先查是否绑定过id
                    const res = await getDotaIdList({
                        wechatId: contact.id
                    })
                    if (res.data.length > 0) {
                        let message = ''
                        for (const userId of res.data) {
                            let result = await getRecord(userId)
                            console.log(result)
                            message = message + result + '\n'
                        }
                        resolve(message)
                    } else {
                        reject('请输入或绑定dota2好友ID!')
                    }
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 查询队友
    getTeammate(userId, msg) {
        return new Promise(async (resolve, reject) => {
            try {
                if (userId) {
                    const message = await getPeer(userId)
                    resolve(message)
                } else {
                    let contact = msg.talker();
                    // 先查是否绑定过id
                    const res = await getDotaIdList({
                        wechatId: contact.id
                    })
                    if (res.data.length > 0) {
                        let message = ''
                        for (const userId of res.data) {
                            let result = await getPeer(userId)
                            message = message + result + '\n'
                        }
                        resolve(message)
                    } else {
                        reject('请输入或绑定dota2好友ID!')
                    }
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 查询统计
    getStatistics(userId, msg) {
        return new Promise(async (resolve, reject) => {
            try {
                if (userId) {
                    const message = await getTotal(userId)
                    resolve(message)
                } else {
                    let contact = msg.talker();
                    // 先查是否绑定过id
                    const res = await getDotaIdList({
                        wechatId: contact.id
                    })
                    if (res.data.length > 0) {
                        let message = ''
                        for (const userId of res.data) {
                            let result = await getTotal(userId)
                            message = message + result + '\n'
                        }
                        resolve(message)
                    } else {
                        reject('请输入或绑定dota2好友ID!')
                    }
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 查询英雄
    getHero(userId, msg) {
        return new Promise(async (resolve, reject) => {
            try {
                if (userId) {
                    const message = await getHeroTotal(userId)
                    resolve(message)
                } else {
                    let contact = msg.talker();
                    // 先查是否绑定过id
                    const res = await getDotaIdList({
                        wechatId: contact.id
                    })
                    if (res.data.length > 0) {
                        let message = ''
                        for (const userId of res.data) {
                            let result = await getHeroTotal(userId)
                            message = message + result + '\n'
                        }
                        resolve(message)
                    } else {
                        reject('请输入或绑定dota2好友ID!')
                    }
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 查询词云
    getWordCloud(userId, msg) {
        return new Promise(async (resolve, reject) => {
            try {
                if (userId) {
                    const message = await getWordcloud(userId)
                    resolve(message)
                } else {
                    let contact = msg.talker();
                    // 先查是否绑定过id
                    const res = await getDotaIdList({
                        wechatId: contact.id
                    })
                    if (res.data.length > 0) {
                        let message = ''
                        for (const userId of res.data) {
                            let result = await getWordcloud(userId)
                            message = message + result + '\n'
                        }
                        resolve(message)
                    } else {
                        reject('请输入或绑定dota2好友ID!')
                    }
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 查询历史
    getHistory(userId, msg) {
        return new Promise(async (resolve, reject) => {
            try {
                if (userId) {
                    const message = await getHistory(userId)
                    resolve(message)
                } else {
                    let contact = msg.talker();
                    // 先查是否绑定过id
                    const res = await getDotaIdList({
                        wechatId: contact.id
                    })
                    if (res.data.length > 0) {
                        let message = ''
                        for (const userId of res.data) {
                            let result = await getHistory(userId)
                            message = message + result + '\n'
                        }
                        resolve(message)
                    } else {
                        reject('请输入或绑定dota2好友ID!')
                    }
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 添加监控
    addMonitorMember(monitorMemberId, msg) {
        return new Promise(async (resolve, reject) => {
            try {
                if (monitorMemberId) {
                    if (typeof monitorMemberId === 'number') {
                        if (await isOpenUser(monitorMemberId)) {
                            let contact = msg.talker();
                            const room = msg.room();
                            const topic = await room.topic();
                            const res = await addMonitorMember({
                                topic,
                                userId: contact.id,
                                monitorMemberId
                            })
                            if (res.code === 200) {
                                resolve('操作成功!')
                            } else {
                                reject(res.data)
                            }
                        } else {
                            reject('请输入正确的游戏ID或公开你的游戏数据')
                        }
                    } else {
                        reject('输入格式有误!')
                    }
                } else {
                    reject('请输入DOTA2好友ID!')
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 移除监控
    removeMonitorMember(monitorMemberId, msg) {
        return new Promise(async (resolve, reject) => {
            try {
                if (monitorMemberId) {
                    if (typeof monitorMemberId === 'number') {
                        if (await isOpenUser(monitorMemberId)) {
                            let contact = msg.talker();
                            const room = msg.room();
                            const topic = await room.topic();
                            const res = await removeMonitorMember({
                                topic,
                                userId: contact.id,
                                monitorMemberId
                            })
                            if (res.code === 200) {
                                resolve('操作成功!')
                            } else {
                                reject(res.data)
                            }
                        } else {
                            reject('请输入正确的游戏ID或公开你的游戏数据')
                        }
                    } else {
                        reject('输入格式有误!')
                    }
                } else {
                    reject('请输入DOTA2好友ID!')
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 清除监控
    clearMonitorMember(msg) {
        return new Promise(async (resolve, reject) => {
            try {
                let contact = msg.talker();
                const room = msg.room();
                const topic = await room.topic();
                const res = await clearMonitorMember({
                    topic,
                    userId: contact.id
                })
                if (res.code === 200) {
                    resolve('操作成功!')
                } else {
                    reject(res.data)
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 监控列表
    getMonitorMemberList(msg) {
        return new Promise(async (resolve, reject) => {
            try {
                const room = msg.room();
                const topic = await room.topic();
                const res = await getMonitorMemberList({ topic })
                if (res.code !== 200) {
                    reject(res.data)
                } else {
                    const monitorMemberList = res.data
                    if (monitorMemberList.length === 0) {
                        reject('监控列表暂时无人')
                    } else {
                        const nameList = await getNameListByUserIdList(monitorMemberList)
                        if (nameList.length > 0) {
                            let message = `\n====监控列表[${nameList.length}/10]====\n`
                            message = message + nameList.join('\n')
                            resolve(message)
                        } else {
                            reject('监控列表暂时无人')
                        }
                    }
                }
            } catch (error) {
                console.log(error)
                reject(error)
            }
        })
    }

    // 添加绑定
    bindDotaId(dotaId, msg) {
        return new Promise(async (resolve, reject) => {
            try {
                if (dotaId) {
                    dotaId = Number(dotaId)
                    if (typeof dotaId == 'number') {
                        if (await isOpenUser(dotaId)) {
                            let contact = msg.talker()
                            const res = await bindDotaId({
                                wechatId: contact.id,
                                dotaId
                            })
                            if (res.code === 200) {
                                resolve('操作成功!')
                            } else {
                                reject(res.data)
                            }
                        } else {
                            reject('请输入正确的游戏ID或公开你的游戏数据')
                        }
                    } else {
                        reject('请输入正确游戏ID!')
                    }
                } else {
                    reject('请输入DOTA2好友ID!')
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 解除绑定
    unbindDotaId(dotaId, msg) {
        return new Promise(async (resolve, reject) => {
            try {
                if (dotaId) {
                    dotaId = Number(dotaId)
                    if (typeof dotaId == 'number') {
                        if (await isOpenUser(dotaId)) {
                            let contact = msg.talker()
                            const res = await unbindDotaId({
                                wechatId: contact.id,
                                dotaId
                            })
                            if (res.code === 200) {
                                resolve('操作成功!')
                            } else {
                                reject(res.data)
                            }
                        } else {
                            reject('请输入正确的游戏ID或公开你的游戏数据')
                        }
                    } else {
                        reject('请输入正确游戏ID!')
                    }
                } else {
                    reject('请输入DOTA2好友ID!')
                }
            } catch (error) {
                reject(error)
            }
        })
    }


    // 绑定列表
    getDotaIdList(msg) {
        return new Promise(async (resolve, reject) => {
            try {
                let contact = msg.talker()
                const res = await getDotaIdList({
                    wechatId: contact.id
                })
                if (res.code === 200) {
                    if (res.data.length > 0) {
                        const nameList = await getNameListByUserIdList(res.data)
                        let message = `\n====绑定列表[${res.data.length}/3]====\n`
                        message = message + nameList.join('\n')
                        resolve(message)
                    } else {
                        reject('暂时绑定任何id')
                    }
                } else {
                    reject(res.data)
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 清除绑定
    clearDotaIdList(msg) {
        return new Promise(async (resolve, reject) => {
            try {
                let contact = msg.talker()
                const res = await clearDotaIdList({
                    wechatId: contact.id
                })
                if (res.code === 200) {
                    resolve('操作成功!')
                } else {
                    reject(res.data)
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 双色球
    getTwoColorBall() {
        return new Promise((resolve, reject) => {
            try {
                let redBall = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
                let blueBall = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
                let redBallResult = []
                let blueBallResult = []
                blueBall.sort(() => Math.random() - 0.5)
                while (redBallResult.length < 6) {
                    redBall.sort(() => Math.random() - 0.5)
                    redBallResult.push(redBall.pop())
                }
                blueBallResult.push(blueBall.pop())
                resolve(`${redBallResult.sort((a, b) => { return a - b }).join(' ')} +${blueBallResult.toString()}`)
            } catch (error) {
                reject(error)
            }
        })
    }

    // 神回复
    getGod() {
        return new Promise((resolve, reject) => {
            getGodreply().then(res => {
                if (res.code === 200 && res.newslist.length > 0) {
                    resolve(`\n${res.newslist[0].title}\n\n${res.newslist[0].content}`)
                } else {
                    resolve('什么都没有找到啦[旺柴]')
                }
            }).catch(e => {
                reject(e)
            })
        })
    }

    // 早安
    getGoodMorning() {
        return new Promise((resolve, reject) => {
            getGoodMorningReply().then(res => {
                if (res.code === 200 && res.newslist.length > 0) {
                    resolve(`\n${res.newslist[0].content}`)
                } else {
                    resolve('什么都没有找到啦[旺柴]')
                }
            }).catch(e => {
                reject(e)
            })
        })
    }

    // 晚安
    getGoodNight() {
        return new Promise((resolve, reject) => {
            getGoodNightReply().then(res => {
                if (res.code === 200 && res.newslist.length > 0) {
                    resolve(`\n${res.newslist[0].content}`)
                } else {
                    resolve('什么都没有找到啦[旺柴]')
                }
            }).catch(e => {
                reject(e)
            })
        })
    }

    // 历史上的今天
    getTodayInHistory() {
        return new Promise(async (resolve, reject) => {
            try {
                const today = await getToday()
                const res = await getHistoryToday(today)
                if (res.code === 200 && res.newslist.length > 0) {
                    let message = '\n'
                    res.newslist.forEach(news => {
                        message += `[${news.lsdate}]${news.title}\n`
                    })
                    resolve(message)
                } else {
                    resolve('什么都没有找到啦[旺柴]')
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 抽签
    getDraw(msg) {
        return new Promise(async (resolve, reject) => {
            try {
                const today = new Date().toLocaleDateString()
                if (['2022-1-30', '2022-1-31', '2022-2-1', '2022-2-2', '2022-2-3'].includes(today)) {
                    const goods = [
                        '生活如意，事业高升，年年今日，岁岁今朝',
                        '前程似锦，美梦成真，日新月异，财源滚滚',
                        '美满幸福，和气致祥，事事顺利，万事如意',
                        '荣华富贵，大展宏图，家庭幸福，前途无量',
                        '年年有鱼，生意兴隆，财源广进，长命百岁',
                        '步步高升，龙凤呈祥，一帆风顺，万事大吉',
                        '万事胜意，阖家辛福，兴业来者，龙有传人',
                        '松柏同春，华堂偕老，桃开连理，一帆风顺',
                        '蒸蒸日上，日新月异，身体健康，合家富贵',
                        '吉祥如意，意气风发，好事连连，寿与天齐'
                    ]
                    resolve(`\n运势:新年大吉[福]\n分数:100[烟花]\n结论:${goods[Math.ceil(Math.random() * goods.length - 1)]}[爆竹][庆祝][爆竹][庆祝][爆竹][庆祝]`)
                }
                let contact = msg.talker();
                const jxNumber = (await getJxnumber({ wechatId: contact.id })).data
                const res = await getJixiong(jxNumber)
                if (res.code === 200 && res.newslist.length > 0) {
                    resolve(`\n运势:${res.newslist[0].result}\n分数:${res.newslist[0].score}\n结论:${res.newslist[0].conclusion}\n如若不满意结果，可输入'重新抽签'`)
                } else {
                    resolve('什么都没有找到啦[旺柴]')
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 重新抽签
    getDrawAgain(msg) {
        return new Promise(async (resolve, reject) => {
            try {
                let contact = msg.talker();
                const jxNumberRes = await getJxnumberAgain({ wechatId: contact.id })
                if (jxNumberRes.code == 200) {
                    const { jxNumber, jxCount } = jxNumberRes.data
                    const res = await getJixiong(jxNumber)
                    if (res.code === 200 && res.newslist.length > 0) {
                        resolve(`\n这是您今天第${jxCount}次重新抽签\n运势:${res.newslist[0].result}\n分数:${res.newslist[0].score}\n结论:${res.newslist[0].conclusion}\n如若不满意结果，可输入'重新抽签'`)
                    } else {
                        resolve('什么都没有找到啦[旺柴]')
                    }
                } else {
                    resolve(jxNumberRes.data)
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 星座运势
    getStarFortune(star) {
        return new Promise((resolve, reject) => {
            getStar(encodeURI(star)).then(res => {
                if (res.code === 200 && res.newslist.length > 0) {
                    let message = '\n'
                    res.newslist.forEach(news => {
                        message += `${news.type}:${news.content}\n`
                    })
                    resolve(message)
                } else {
                    resolve('什么都没有找到啦[旺柴]')
                }
            }).catch(e => {
                reject(e)
            })
        })
    }

    // 刀塔运势
    getDotaFortune(msg) {
        return new Promise(async (resolve, reject) => {
            try {
                let contact = msg.talker();
                const { today, goodList, badList, directionValue, drinkValue, goddesValue } = (await getDotaFortuneByWechatId({ wechatId: contact.id })).data
                let goodResultList = []
                goodList.forEach(item => {
                    goodResultList.push(`【${item.name}----${item.good}】`)
                })
                let goodResult = goodResultList.join('\n')
                let badResultList = []
                badList.forEach(item => {
                    badResultList.push(`【${item.name}----${item.bad}】`)
                })
                let badResult = badResultList.join('\n')
                let message = `\n${today}\n宜：\n${goodResult}\n忌：\n${badResult}\n座位朝向：面向${directionValue}打DOTA2，胜率最高。\n今日宜饮：${drinkValue}\n超神指数：${goddesValue}`
                resolve(message)
            } catch (error) {
                reject(error)
            }
        })
    }

    getRandomHero(msg) {
        return new Promise(async (resolve, reject) => {
            try {
                const hero = randomHero()
                const message = `你随机选择了${hero}`
                resolve(message)
            } catch (error) {
                reject(error)
            }
        })
    }


    playDota(msg) {
        return new Promise(async (resolve, reject) => {
            try {
                const room = msg.room();
                let contact = msg.talker();
                let playerId = await contact.id
                let playerName = await contact.name()
                let roomName = await room.topic()
                const res = await playDotaGame({ playerId, playerName, roomName, result: '' })
                if (res.code == 200) {
                    let optionString = ''
                    if (res.data.options) {
                        res.data.options.forEach(item => {
                            optionString += `${item.content}\n`
                        })
                    }
                    resolve(`${res.data.content}\n${optionString}`)
                } else {
                    resolve(res.data)
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    dotaMessageHandler() {

    }

    getOlympic() {
        return new Promise(async (resolve, reject) => {
            try {
                let date = new Date()
                let today = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
                axios.get(`https://ugclandpage.pae.baidu.com/api/asyncfullcolumn?srcid=50523&full_column_event=tokyo_olympic_2021&query=${today}`).then(res => {
                    let message = ''
                    res.data.data.dataList.forEach(item => {
                        message += `\n[${item.startDate} ${item.startTime} ${item.eventStatusName}] ${item.discipline.name} ${item.description} ${item.vsTextFmt ? item.vsTextFmt : ''}`
                    })
                    resolve(message)
                })
            } catch (error) {
                reject(error)
            }
        })
    }

    getChinaGold() {
        return new Promise(async (resolve, reject) => {
            try {
                axios.get('https://ugclandpage.pae.baidu.com/api/asyncfullcolumn?srcid=50522&full_column_event=tokyo_olympic_2021&query=%E4%B8%AD%E5%9B%BD%E9%87%91%E7%89%8C').then(res => {
                    let message = ''
                    res.data.data.dataList.forEach(item => {
                        message += `\n第${item.number}枚 ${item.date} ${item.title} ${item.subTitle}`
                    })
                    resolve(message)
                })
            } catch (error) {
                reject(error)
            }
        })
    }

    // 生日性格
    getNatureByBirthday(birthday) {
        return new Promise(async (resolve, reject) => {
            const m = birthday.split('.')[0]
            const d = birthday.split('.')[1]
            const res = await getBirthDay(m, d).then(res => {
                if (res.code === 200 && res.newslist.length > 0) {
                    let message = `\n${res.newslist[0].title}\n${res.newslist[0].content}`
                    resolve(message)
                } else {
                    resolve('什么都没有找到啦[旺柴]')
                }
            }).catch(e => {
                reject(e)
            })
        })
    }

    // 藏头诗
    getPoetry(word) {
        return new Promise(async (resolve, reject) => {
            try {
                if (word.length >= 2 && word.length <= 8) {
                    const res = await getCangtoushi(encodeURI(word))
                    if (res.code === 200 && res.newslist.length > 0) {
                        let message = '\n'
                        res.newslist.forEach(news => {
                            message += `${news.list}\n\n`
                        })
                        resolve(message)
                    } else {
                        resolve('什么都没有找到啦[旺柴]')
                    }
                } else {
                    resolve('请输入2~8个字哦')
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 解梦
    getDreamAbout(word) {
        return new Promise((resolve, reject) => {
            getDream(encodeURI(word)).then(res => {
                if (res.code === 200 && res.newslist.length > 0) {
                    let message = `\n${res.newslist[0].result.replace(/<br>/g, "\n")}`
                    resolve(message)
                } else {
                    resolve('什么都没有找到啦[旺柴]')
                }
            }).catch(e => {
                reject(e)
            })
        })
    }

    // 查询积分
    getScore(msg) {
        return new Promise(async (resolve, reject) => {
            try {
                let contact = msg.talker();
                const score = (await getScore({ playerId: contact.id })).data
                if (score) {
                    resolve(`\n你的总积分为【${score}】`)
                } else {
                    resolve('什么都没有找到啦[旺柴]')
                }
            } catch (error) {
                reject(error)
            }
        })
    }

    // 查询积分排名
    getScoreRank(msg) {
        return new Promise(async (resolve, reject) => {
            try {
                let room = msg.room();
                const roomName = await room.topic();
                const { data } = await getScoreRank({ roomName })
                let roomPlayerList = data.room
                let allPlayerList = data.all
                let message = `\n===本群积分榜===\n`
                if (roomPlayerList.length > 0) {
                    roomPlayerList = roomPlayerList.length > 5 ? roomPlayerList.slice(0, 4) : roomPlayerList
                    roomPlayerList.forEach((item, index) => {
                        message += `【${index + 1}】 ${item.playerName}[${item.playerScore}分]\n`
                    })
                } else {
                    message += '本群还没有人参与过问答\n'
                }
                message += '\n===总积分榜===\n'
                if (allPlayerList.length > 0) {
                    allPlayerList = allPlayerList.length > 5 ? allPlayerList.slice(0, 4) : allPlayerList
                    allPlayerList.forEach((item, index) => {
                        message += `【${index + 1}】 ${item.playerName}[${item.playerScore}分]\n`
                    })
                } else {
                    message += '还没有人参与过问答\n'
                }
                resolve(message)
            } catch (error) {
                reject(error)
            }
        })
    }
}

module.exports = {
    messageManager
}